import tkinter as tk
from tkinter import messagebox

class PasswordBox(tk.Toplevel):
    def __init__(self, master, title="Enter Password"):
        super().__init__(master)
        self.title(title)
        self.geometry("300x150")  # 设置窗口大小
        self.resizable(False, False)  # 禁止调整窗口大小
        
        # 创建一个标签说明输入内容
        self.label = tk.Label(self, text="Please enter your password:")
        self.label.pack(pady=(0, 10), padx=20, anchor='nw')

        # 创建一个密码输入框
        self.password_entry = tk.Entry(self, show="*")  # 使用show="*"隐藏密码
        self.password_entry.pack(pady=(0, 10), padx=20, fill=tk.X, expand=True)

        # 创建确定和取消按钮
        self.confirm_button = tk.Button(self, text="OK", command=self.on_confirm)
        self.cancel_button = tk.Button(self, text="Cancel", command=self.on_cancel)

        self.confirm_button.pack(side=tk.RIGHT, padx=(0, 20))
        self.cancel_button.pack(side=tk.RIGHT)

        # 绑定Enter键到确认按钮
        self.bind('<Return>', self.on_confirm)

    def on_confirm(self, event=None):
        """当用户点击确定按钮时调用此函数"""
        self.password = self.password_entry.get()  # 获取密码
        self.result = True  # 设置结果为True，表示用户点击了确定
        self.destroy()  # 关闭窗口

    def on_cancel(self, event=None):
        """当用户点击取消按钮时调用此函数"""
        self.result = False  # 设置结果为False，表示用户点击了取消
        self.password = None
        self.destroy()  # 关闭窗口

    def show(self):
        """显示消息框并等待用户操作"""
        self.wait_window(self)  # 阻塞直到消息框关闭
        return self.result, self.password  # 返回结果和密码


# 使用示例
if __name__ == "__main__":
    root = tk.Tk()
    root.geometry("200x100")  # 设置主窗口大小

    def show_custom_dialog():
        custom_dialog = PasswordBox(root)
        result, password = custom_dialog.show()
        if result:
            messagebox.showinfo("Success", f"You entered: {password}")
        else:
            messagebox.showwarning("Cancelled", "You cancelled the operation.")

    show_button = tk.Button(root, text="Show Password Dialog", command=show_custom_dialog)
    show_button.pack(pady=50)

    root.mainloop()